using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace AdminApiTemplate.Common.Helpers
{
    /// <summary>
    /// 
    /// </summary>
    public static class CTEHelp
    {
        /// <summary>
        /// 根据跟节点ID获得模拟的树列表
        /// </summary>
        /// <typeparam name="T">数据实体</typeparam>
        /// <typeparam name="TEquer">用于比较的属性类型</typeparam>
        /// <param name="list">数据源</param>
        /// <param name="prior">前面记录取值的属性（用于跟后面的对比）</param>
        /// <param name="afterwards">后面一条记录的取值属性（用于跟前面的记录对比）</param>
        /// <param name="StartWith">起源</param>
        /// <param name="lvl">定义的开始层级</param>
        /// <returns></returns>
        public static List<KeyValuePair<int, T>> GetCteLevelEntityList<T, TEquer>(
            this IEnumerable<T> list,
            Func<T, TEquer> prior,
            Func<T, TEquer> afterwards,
            TEquer StartWith,
            int lvl = 0)
        {
            return list
                .Where(x => afterwards(x).Equals(StartWith))
                .SelectMany(x =>
                    new[] { new KeyValuePair<int, T>(lvl, x) }.Concat(GetCteLevelEntityList(list, prior, afterwards, prior(x), lvl + 1))
                ).ToList();
        }

        /// <summary>
        /// 获得字符串
        /// </summary>
        public static string JoinToString<T, TEquer>(this IEnumerable<T> list, Func<T, TEquer> property, char spirator)
        {
            return string.Join(spirator, list.Select(item => property(item).ToString()));
        }
    }
}
